package cn.lg.soar.database.util;

import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;

import javax.sql.DataSource;

/**
 * 数据源工具
 * @author luguoxiang
 * @date 2022/4/30
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public interface DataSourceUtils {

    /**
     * 获取数据源
     * @param properties 据源配置
     * @return
     */
    static DataSource getDataSource(DataSourceProperties properties) {
        return DataSourceBuilder.create()
                .type(properties.getType())
                .driverClassName(properties.getDriverClassName())
                .url(properties.getUrl())
                .username(properties.getUsername())
                .password(properties.getPassword())
                .build();
    }

    /**
     * 获取数据源
     * @param properties 据源配置
     * @param defaultProperties 默认数据源配置
     * @return
     */
    static DataSource getDataSource(DataSourceProperties properties, DataSourceProperties defaultProperties) {
        // 默认值
        if (properties.getType() == null) {
            properties.setType(defaultProperties.getType());
        }
        if (properties.getDriverClassName() == null) {
            properties.setDriverClassName(defaultProperties.getDriverClassName());
        }
        if (properties.getUsername() == null) {
            properties.setUsername(defaultProperties.getUsername());
        }
        if (properties.getPassword() == null) {
            properties.setPassword(defaultProperties.getPassword());
        }
        return getDataSource(properties);
    }

}
